package edu.kaifadui.lmbase.controller;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import edu.kaifadui.lmbase.jwt.DevLoginToken;
import edu.kaifadui.lmbase.vo.Result;
import edu.kaifadui.lmbase.vo.TencentMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 陈世杰
 * @date 2022/2/25 10:47
 * @email dualseason@qq.com
 */
@RestController
public class TencentCloudServiceController {

    @Value("AKID86oFPIvHo56qITO2OTHo42j9ICqEK9gw")
    private String secretId;
    @Value("1lDOJwJPEm34nGSMzMRFm32kBLEpthFV")
    private String secretKey;
    @Value("1400636198")
    private String smsSdkAppId;
    @Value("1314815")
    private String templateId;
    @Value("岭梦开发队")
    private String signName;

    @DevLoginToken
    @PostMapping("/tencent-cloud-message-service/sms")
    public Result sendTencentCloudMessage(@RequestBody TencentMessage tencentMessage) {
        try {
            Credential cred = new Credential(secretId, secretKey);
            SmsClient client = new SmsClient(cred, "ap-nanjing");
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86"+tencentMessage.getPhone()};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId(smsSdkAppId);
            req.setTemplateId(templateId);
            req.setSignName(signName);
            int code = (int) ((Math.random() * 9 + 1) * 100000);
            String[] params = new String[]{String.valueOf(code)};
            req.setTemplateParamSet(params);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            String json = SendSmsResponse.toJsonString(resp);
            if (json.contains("\"Code\":\"Ok\"")) {
                return new Result(200, code, "发送成功");
            } else {
                return new Result(0, "发送失败");
            }
        } catch (TencentCloudSDKException e) {
            return new Result(0, e.toString(), "未知错误");
        }
    }
}
